//
//  ViewController.m
//  FengSiriDemo
//
//  Created by Feng on 2021/7/28.
//

#import "ViewController.h"
#import "SceneControlIntent.h"
#import <Intents/Intents.h>
#import <IntentsUI/IntentsUI.h>

#import "FengAppExtensionHelper.h"
#import "FengSiriService.h"

@interface ViewController ()<INUIAddVoiceShortcutViewControllerDelegate, INUIEditVoiceShortcutViewControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [INPreferences requestSiriAuthorization:^(INSiriAuthorizationStatus status) {
    [[FengSiriService shareInstance] requestSiriAuthWithCompeletion:^(INSiriAuthorizationStatus status) {
        switch (status) {
            case INSiriAuthorizationStatusNotDetermined:
                NSLog(@"用户尚未对该应用程序作出选择。");
                break;
            case INSiriAuthorizationStatusRestricted:
                NSLog(@"此应用程序无权使用Siri服务");
                break;
            case INSiriAuthorizationStatusDenied:
                NSLog(@"用户已明确拒绝此应用程序的授权");
                break;
            case INSiriAuthorizationStatusAuthorized:
                NSLog(@"用户可以使用此应用程序的授权");
                break;
            default:
                break;
        }
    }];
    
    [FengSiriService shareInstance].sceneIntentClassName = @"SceneControlIntent";
    
    [self initSiriConfig];
}

#pragma mark --Siri配置
- (void)initSiriConfig {
    NSDictionary *siriData = @{
        @"baseUrl": @"https://api.akeeta.tech:8143/",
        @"appKey":@"fc49291a7a4d4b438fb00e77a3639406",
        @"appSecret":@"8b2fccea892343b59ff925ab67a579de",
        @"accessToken":@"219bf4cb25b74406946298f1d5823664"
    };
    [FengAppExtensionHelper cacheSiriData:siriData];
}
#pragma mark --获取Siri列表

- (IBAction)siriItemListButtonOnClick:(id)sender {
    [[FengSiriService shareInstance] getShortcutList:@"SceneControlIntent" compeletion:^(NSArray<NSDictionary *> * _Nonnull list) {
        NSLog(@"已添加的siri-shortcut:%@",list);
    }];
//    [self fethShortcutList];
}

#pragma mark --添加Siri快捷键盘

- (IBAction)addSiriItemButtonOnClick:(id)sender {
NSDictionary *dic =  @{
        @"intentType" : @"SceneControlIntent",
        @"shortcutInfo" : @{
            @"sceneId": @"67732",
            @"sceneName": @"灯",
        }
     };
    
    [[FengSiriService shareInstance] addSiriShortcut:dic compeletion:^(MSLSiriServiceAddResult resultCode, NSString * _Nonnull msg) {
        
    }];
    
//    [self addShortcut];
}

#pragma mark --编辑Siri快捷键盘

- (IBAction)editSiriItemButtonOnClick:(id)sender {
    NSDictionary *dic =  @{
        @"intentType" : @"SceneControlIntent",
        @"shortcutInfo" : @{
            @"sceneId": @"67732",
            @"siriId": @"0",
        }
     };
    [[FengSiriService shareInstance] editShortcut:dic compeletion:^(MSLSiriServiceEditResult resultCode, NSString * _Nonnull msg, NSString * _Nonnull invocationPhrase) {
        
    }];
    
//    [self editShortcut];
}

#pragma mark --------------------------------------------简单版本
-(void)fethShortcutList {
    [[INVoiceShortcutCenter sharedCenter] getAllVoiceShortcutsWithCompletion:^(NSArray<INVoiceShortcut *> * _Nullable voiceShortcuts, NSError * _Nullable error) {
        NSMutableArray *temp = [NSMutableArray array];
        if (!error) {
            Class intentClass = NSClassFromString(@"SceneControlIntent"); //自定义意图class
            for (INVoiceShortcut *shortcut in voiceShortcuts) {
                INIntent *intent = shortcut.shortcut.intent;
                if ([intent isKindOfClass:intentClass]) {
                    NSMutableDictionary *shortcutInfo = [NSMutableDictionary dictionary];
                    [shortcutInfo setObject:[intent valueForKey:@"sceneId"] forKey:@"sceneId"];
                    [shortcutInfo setObject:[intent valueForKey:@"siriId"] forKey:@"siriId"];
                    [shortcutInfo setObject:shortcut.invocationPhrase forKey:@"invocationPhrase"];
                    [temp addObject:shortcutInfo];
                }
            }
        }
        NSLog(@"已添加的siri-shortcut:%@",temp);
    }];
}
-(void)addShortcut {
    SceneControlIntent *intent = [[SceneControlIntent alloc] init];
    intent.sceneName = @"Feng";
    intent.sceneId = @"1";
    intent.siriId = @"91";
    intent.suggestedInvocationPhrase = @"打开卧室灯";

    INInteraction *interaction = [[INInteraction alloc] initWithIntent:intent response:nil];
    [interaction donateInteractionWithCompletion:^(NSError * _Nullable error) {
        if(error){
            NSLog(@"%@",error);
        }else{
            NSLog(@"donate success");
        }
    }];

    INShortcut *shortCut = [[INShortcut alloc] initWithIntent:intent];
    INUIAddVoiceShortcutViewController *shortCutVC = [[INUIAddVoiceShortcutViewController alloc] initWithShortcut:shortCut];
    shortCutVC.delegate = self;
    [self presentViewController:shortCutVC animated:YES completion:nil];
}

-(void)editShortcut {
    NSString *sceneId = @"1";
    NSString *siriId = @"91";
    [[INVoiceShortcutCenter sharedCenter] getAllVoiceShortcutsWithCompletion:^(NSArray<INVoiceShortcut *> * _Nullable voiceShortcuts, NSError * _Nullable error) {
        if (error) {
            NSLog(@"%s %d 编辑失败",__func__,__LINE__);
            return;
        }
        BOOL exist = NO;
        INVoiceShortcut *voiceShortcut = nil;
        for (INVoiceShortcut *shortcut in voiceShortcuts) {
            INIntent *intent = shortcut.shortcut.intent;
            if ([[intent valueForKey:@"sceneId"] isEqualToString:sceneId] &&
                [[intent valueForKey:@"siriId"] isEqualToString:siriId]) {
                exist = YES;
                voiceShortcut = shortcut;
                break;
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            NSError *findError = nil;
            if (!exist) {
                findError = [NSError errorWithDomain:@"找不到Siri捷径" code:-1 userInfo:nil];
                NSLog(@"%s %d 编辑失败",__func__,__LINE__);
            }else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    INUIEditVoiceShortcutViewController *shortCutVc = [[INUIEditVoiceShortcutViewController alloc] initWithVoiceShortcut:voiceShortcut];
                    shortCutVc.delegate = self;
                    shortCutVc.modalPresentationStyle = UIModalPresentationFullScreen;
                    [self presentViewController:shortCutVc animated:YES completion:nil];
                });
            }
        });
    }];
}
#pragma mark - add voice delegate
-(void)addVoiceShortcutViewController:(INUIAddVoiceShortcutViewController *)controller didFinishWithVoiceShortcut:(INVoiceShortcut *)voiceShortcut error:(NSError *)error {
    NSLog(@"%s %d 添加完成，结果：%@",__func__,__LINE__,error);
    if (!error) {
        [controller dismissViewControllerAnimated:YES completion:nil];
    }
}

-(void)addVoiceShortcutViewControllerDidCancel:(INUIAddVoiceShortcutViewController *)controller {
    NSLog(@"%s %d 取消添加",__func__,__LINE__);
    [controller dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - edit voice delegate
- (void)editVoiceShortcutViewController:(INUIEditVoiceShortcutViewController *)controller didUpdateVoiceShortcut:(nullable INVoiceShortcut *)voiceShortcut error:(nullable NSError *)error  API_AVAILABLE(ios(12.0)){
    NSLog(@"%s %d 编辑结果：%@",__func__,__LINE__,error);
    if (!error) {
        [controller dismissViewControllerAnimated:YES completion:^{

        }];
    }
}

- (void)editVoiceShortcutViewController:(INUIEditVoiceShortcutViewController *)controller didDeleteVoiceShortcutWithIdentifier:(NSUUID *)deletedVoiceShortcutIdentifier  API_AVAILABLE(ios(12.0)){
    NSLog(@"%s %d 删除成功",__func__,__LINE__);
    [controller dismissViewControllerAnimated:YES completion:^{

    }];
}

- (void)editVoiceShortcutViewControllerDidCancel:(INUIEditVoiceShortcutViewController *)controller  API_AVAILABLE(ios(12.0)){
    NSLog(@"%s %d 取消编辑",__func__,__LINE__);
    [controller dismissViewControllerAnimated:YES completion:^{

    }];
}

@end
